Formius.Element_Select = $.inherit(Formius.Element_Abstract, {

	_relation: {
		options: [],
		field: null,
		rules: []
	},


	__constructor: function(element, parent) {
		this.__base(element, parent);
		var rel;
		if ((rel = this.getOption('relations')) && Formius.Helper.isObject(rel) && rel.field && $.isArray(rel.rules)) {
			this.setRelationRules(rel.field, rel.rules);
//			console.log(this._relation.options);
		}
	},

	relationHandler: function(init) {
		if (this.getParent().isTemplate()) {
			return;
		}
		init = init || false;
		var value = '' + this._relation.field.getValue(),
			activeRules = [],
			selected = this.getElement().find('option:selected').val(),
			countOptions = this._relation.options.length,
			i, j;
		this.getElement().find('option').remove();
		for (i = this._relation.rules.length - 1; i >= 0; i--) {
			if (this._relation.rules[i].from.test(value)) {
				activeRules.push(this._relation.rules[i]);
			}
		}
		for (i = 0; i < countOptions; i++) {
			for (j = activeRules.length - 1; j >= 0; j--) {
				if (activeRules[j].to.test(this._relation.options[i].value)) {
					this.getElement().append('<option value="' + this._relation.options[i].value +
						'">' + this._relation.options[i].text + '</option>');
					break;
				}
			}
		}
		if (init) {
			this.getElement().find('option[value=' + selected + ']:first').attr('selected', 'selected');
		}
	},
	setRelationRules: function(field, rules) {
		var fieldElement = this.getParent().getElementByName(field),
			self = this;
		if (fieldElement && $.isArray(rules)) {
			this._relation.field = fieldElement;
			this._relation.rules = [];
			for (var i = 0; i < rules.length; i++) {
				if (Formius.Helper.isObject(rules[i]) && rules[i].from && rules[i].to) {
					this._relation.rules.push({
						from: new RegExp(rules[i].from),
						to: new RegExp(rules[i].to)
					});
				}
			}
			this._relation.options = [];
			this.getElement().find('option').each(function(i, option) {
				self._relation.options.push({
					value: option.value,
					text: option.text
				});
			});
			this._relation.field.bind('change', function() {
				self.relationHandler();
			});
			this.relationHandler(true);
		}
	}
});